package com.bjesc_b2c.app.appraiset.mvp.view.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.TextView;

import com.bjesc_b2c.app.appraiset.MyApplication;
import com.bjesc_b2c.app.appraiset.R;
import com.bjesc_b2c.app.appraiset.base.BaseActivity;
import com.bjesc_b2c.app.appraiset.http.IApiActivityRequest;
import com.bjesc_b2c.app.appraiset.mvp.presenter.LoginPresenter;
import com.bjesc_b2c.app.appraiset.mvp.presenter.impl.LoginPersenterImpl;
import com.bjesc_b2c.app.appraiset.mvp.view.LoginView;
import com.bjesc_b2c.app.appraiset.utils.UpdateManager;
import com.example.codeutils.utils.AppUtils;
import com.example.codeutils.utils.RSAUtil;
import com.orhanobut.logger.Logger;
import com.rxretrofit_build.model.RxBusBean;
import com.rxretrofit_build.util.CustomSharedPreferences;
import com.rxretrofit_build.util.MapUtil;
import com.tencent.bugly.crashreport.CrashReport;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.OnClick;
import master_bean.AppUpdateBean;
import rxretrofit_base.model.FileLoadingBean;
import rxretrofit_base.model.KeyBean;
import rxretrofit_base.model.ShowType;
import rxretrofit_base.model.TokenBean;
import rxretrofit_base.net.BaseSubscriber;
import rxretrofit_base.net.RxRequest;

/**
 * Created by Jason Chen on 2017/2/20.
 * 登录
 */
public class LoginActivity extends BaseActivity implements LoginView {
    @Bind(R.id.edit_username)
    EditText usernameEdit;
    @Bind(R.id.edit_password)
    EditText passwordEdit;
    @Bind(R.id.appVersionNameTv)
    TextView appVersionTv;
    private LoginPresenter loginPersenter;
    private String username;
    private String password;
    private boolean isClick = true;
    private ProgressDialog mProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_login;
    }

    @Override
    protected void createPresenter() {
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {//安装按home键重复打开页面的问题
            finish();
            return;
        }
        checkGalleryPermission();
        loginPersenter = new LoginPersenterImpl(this);
    }

    @Override
    protected void initEventAndData() {
        Logger.d(MyApplication.DIMEN_DPI);
        Logger.d(MyApplication.SCREEN_HEIGHT);
        Logger.d(MyApplication.SCREEN_WIDTH);
        username = CustomSharedPreferences.getString(this, KeyBean.USER_NAME.valueOf(), KeyBean.FILE_NAME.valueOf());
        password = CustomSharedPreferences.getString(this, KeyBean.PASSWORD.valueOf(), KeyBean.FILE_NAME.valueOf());
        if (!TextUtils.isEmpty(username)) {
            usernameEdit.setText(username);
        }
        if (!TextUtils.isEmpty(password)) {
            passwordEdit.setText(password);
        }
        appVersionTv.setText("当前版本号：" + AppUtils.getAppVersionName(this));
        int mVersion_code = AppUtils.getAppVersionCode(this);// 当前的版本号
        Logger.d(mVersion_code + "");
        getVisern(mVersion_code);
    }
    private boolean checkGalleryPermission() {
        int ret = ActivityCompat.checkSelfPermission(LoginActivity.this, Manifest.permission
                .READ_EXTERNAL_STORAGE);
        if (ret != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(LoginActivity.this,
                    new String[] {Manifest.permission.READ_EXTERNAL_STORAGE},
                    1000);
            return false;
        }
        return true;
    }
    @Override
    public void loadStart() {
        showLoading("登录中...");
    }

    @Override
    public void loadCompleted() {
        cancelLoading();
    }

    @Override
    public void loadFailure() {
        cancelLoading();
    }

    private void getVisern(int version) {
        HashMap<String, Object> map = new MapUtil()
                .put("version", version)
                .put("url", true).build();
        RxRequest.request(ShowType.DISMISS, RxRequest.getClient(LoginActivity.this, map).create(IApiActivityRequest.class).appVersion(),
                new BaseSubscriber<TokenBean<AppUpdateBean>>(LoginActivity.this) {
                    @Override
                    public void onSuccess(TokenBean<AppUpdateBean> o) {
                        isClick = true;
                        if (o.getData() != null) {
                            Logger.d("  ==" + o.getData().getUrl());
                            String url = o.getData().getUrl();
                            String version_info = "\t\t\t发现新的版本,是否更新？";
                            showProgressDialog();
                            new UpdateManager(LoginActivity.this).showNoticeDialog(version_info, url, mProgressDialog);
                        } else {
                            autoLogin();
                        }
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        isClick = true;
                    }
                });
    }

    /**
     * 判断密码是否正确，正确就跳转
     */
    @Override
    public void login() {
        //判断账号密码是否正确，如果正确则跳转主界面，如果错误则提示
        HashMap<String, Object> build = new MapUtil()
                .put(KeyBean.USER_NAME.valueOf(), usernameEdit.getText().toString())
                .put(KeyBean.PASSWORD.valueOf(), passwordEdit.getText().toString())
                .build();
        CrashReport.setUserId(usernameEdit.getText().toString()); //设置 bugly 返回用户id
        CustomSharedPreferences.saveString(this, build, KeyBean.FILE_NAME.valueOf());   //保存密码
        startIntent(new Intent(LoginActivity.this, MainActivity.class), true);
    }
    /**
     * 自动登录
     */
    public void autoLogin() {
        if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(password)) {
            try {
                password = RSAUtil.EncryptDataOfPublicKey(password, LoginActivity.this.getResources().openRawResource(R.raw.rsa_public_key));
            } catch (Exception e) {
                e.printStackTrace();
            }
            loginPersenter.requestLogin(username, Uri.encode(password));
        } else {
            showToast("账号密码为空!");
        }
    }

    @OnClick(R.id.btn_login)
    public void onClick() {
        if (isClick) {
            username = usernameEdit.getText().toString();
            password = passwordEdit.getText().toString();
            autoLogin();
        } else {
            showToast("检测更新，请稍后...");
        }
    }

    @Override
    protected void doOnNext(RxBusBean rxBusBean) {
        super.doOnNext(rxBusBean);
        if (rxBusBean.getO() instanceof FileLoadingBean) {
            FileLoadingBean fileLoadingBean = (FileLoadingBean) rxBusBean.getO();
            int progress = (int) (fileLoadingBean.getProgress() * 100 / fileLoadingBean.getTotal());
            mProgressDialog.setProgress(progress);
            if (progress == 99) {
                mProgressDialog.dismiss();
            }
        }
    }

    private void showProgressDialog() {
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setTitle("正在下载");
        mProgressDialog.setMax(100);
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setMessage("请稍候...");
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setCanceledOnTouchOutside(false);
//      mProgressDialog.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
